<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form</title>
  <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
  <script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<script>
  function postData() {
    const data = {};
    data.username = document.getElementById('username').value;
    data.password = document.getElementById('password').value;
    if (/^[A-Z][a-zA-Z0-9]{5,16}$/.test(data.username)) {
      // Fetch API
      // fetch('http://localhost:3000', {
      //   method: 'POST',
      //   body: JSON.stringify(data),
      // }).then(function (response) {
      //   return response.text();
      // }).then(function (text) {
      //   document.getElementById('res').innerText = text;
      // });

      // XMLHttpRequest
      const request = new XMLHttpRequest;
      request.open('POST', 'http://localhost:3000?type=ajax');
      request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
          document.getElementById('res').innerText = request.responseText;
        }
      };
      request.send(JSON.stringify(data));
    } else {
      document.getElementById('res').innerText = '用户名不符合规范';
    }
  }
</script>
<div class="row">
  <div class="col-sm-4 col-sm-offset-4">
    <h1>A Simple Form</h1>
    <form action="http://localhost:3000/?type=form" role='form' method="post">
      <div class="form-group">
        <label for="username">用户名:</label>
        <input class="form-control" type="text" id="username" name="username" placeholder="用户名">
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input class="form-control" type="password" id="password" name="password" placeholder="密码">
      </div>
      <div class="form-group" style="text-align: center">
        <input type="submit" class="btn" value="跳转">
      </div>
    </form>
    <div class="form-group" style="text-align: center">
      <button class="btn" onclick="postData()">Ajax提交</button>
      <div><b id="res"></b></div>
    </div>
  </div>
</div>
</body>
</html>